package com.atguigu.tingshu.album.receiver;

import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author: atguigu
 * @create: 2024-12-03 11:49
 */
@Slf4j
@Component
public class AlbumReceiver {


    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private TrackInfoService trackInfoService;

    /**
     * 监听声音增量更新消息，并更新数据库中统计信息
     *
     * @param trackStatMqVo
     * @param message
     * @param channel
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_TRACK, durable = "true"),
            value = @Queue(value = MqConst.QUEUE_TRACK_STAT_UPDATE, durable = "true"),
            key = MqConst.ROUTING_TRACK_STAT_UPDATE
    ))
    public void updateTrackStat(TrackStatMqVo trackStatMqVo, Message message, Channel channel) {
        if (trackStatMqVo != null) {
            log.info("[专辑服务]监听到增量更新声音统计消息：{}", trackStatMqVo);
            //1.幂等性处理 需要确保同一消息及时被MQ服务器多次投递，消费者只能处理一次消息
            //1.1 构建幂等性唯一标识=前缀:消息业务唯一标识
            String key = RedisConstant.BUSINESS_PREFIX + "db:" + trackStatMqVo.getBusinessNo();
            //1.2 将key尝试存入Redis
            Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, "", RedisConstant.ORDER_TRADE_EXPIRE, TimeUnit.MINUTES);
            if (flag) {
                try {
                    //2.执行业务逻辑
                    trackInfoService.updateTrackStat(trackStatMqVo);
                } catch (Exception e) {
                    log.error("[专辑服务]统计值增量更新异常：{}", e);
                    redisTemplate.delete(key);
                    channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
                    return;
                }
            }
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

}
